package com.cmc6.pay.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alipay.api.AlipayConfig;
import com.alipay.api.internal.util.AlipaySignature;
import com.cmc6.pay.model.dto.AliPayDTO;
import com.cmc6.pay.service.PayService;
import com.cmc6.pay.util.AliPayUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Service
@Slf4j
public class PayServiceImpl implements PayService {

    @Resource
    AlipayConfig alipayConfig;

    @Override
    public String aliPay(AliPayDTO dto) {

        return AliPayUtil.pay(dto);
    }

    /**
     * 服务器异步通知，备注：第三方应用调用
     */
    @SneakyThrows
    @Override
    public String notifyCallBack(HttpServletRequest request) {

        Map<String, String> paramsMap = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            paramsMap.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature
            .rsaCheckV1(paramsMap, alipayConfig.getAlipayPublicKey(), alipayConfig.getCharset(),
                alipayConfig.getSignType()); // 调用SDK验证签名

        if (signVerified) {
            // 商户订单号
            String outTradeNo = new String(request.getParameter("out_trade_no").getBytes(StandardCharsets.ISO_8859_1),
                StandardCharsets.UTF_8);
            // 支付宝交易号
            String tradeNo = new String(request.getParameter("trade_no").getBytes(StandardCharsets.ISO_8859_1),
                StandardCharsets.UTF_8);
            // 付款金额
            String totalAmount = new String(request.getParameter("total_amount").getBytes(StandardCharsets.ISO_8859_1),
                StandardCharsets.UTF_8);
            // 交易状态
            String tradeStatus = new String(request.getParameter("trade_status").getBytes(StandardCharsets.ISO_8859_1),
                StandardCharsets.UTF_8);

            if ("TRADE_SUCCESS".equals(tradeStatus)) {
            }

            log.info("************* 支付成功(支付宝异步通知) - 时间: {} *************", DateUtil.now());
            log.info("* 订单号: {}", outTradeNo);
            log.info("* 支付宝交易号: {}", tradeNo);
            log.info("* 实付金额: {}", totalAmount);
            log.info("* 交易状态: {}", tradeStatus);
            log.info("*****************************************************************************");

            return "success";
        } else {
            return "failure";
        }
    }

}
